package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;

    @Override
    public Cart save(Cart cart) {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, UserHolder.get().getId());
        wrapper.eq(cart.getDishId() != null, Cart::getDishId, cart.getDishId());
        wrapper.eq(cart.getSetmealId() != null, Cart::getSetmealId, cart.getSetmealId());
        Cart cart1 = cartMapper.selectOne(wrapper);
        if (cart1 != null) {
            cart1.setNumber(cart1.getNumber() + 1);
            cartMapper.updateById(cart1);
            return cart1;
        } else {
            cart.setUserId(UserHolder.get().getId());//设置为登录用户id
            cart.setCreateTime(new Date());
            cart.setNumber(1);
            cartMapper.insert(cart);
            return cart;
        }
    }

    //查询购物车
    @Override
    public List<Cart> findList() {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, UserHolder.get().getId());
        wrapper.orderByAsc(Cart::getCreateTime);
        List<Cart> cartList = cartMapper.selectList(wrapper);
        return cartList;
    }

    @Override
    public Cart sub(Long dishId, Long setmealId) {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, UserHolder.get().getId());
        wrapper.eq(dishId != null, Cart::getDishId, dishId);
        wrapper.eq(setmealId != null, Cart::getSetmealId, setmealId);
        Cart cart = cartMapper.selectOne(wrapper);
        if (cart.getNumber() >= 1) {
            cart.setNumber(cart.getNumber() - 1);
            cartMapper.updateById(cart);
            if (cart.getNumber() == 0) {
                cartMapper.deleteById(cart);
            }
        }
        return cart;
    }

    @Override
    public void clean() {
        //根据用户的id将数据库中的信息全部删除
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId,UserHolder.get().getId());
        cartMapper.delete(wrapper);
    }
}
